package com.xbongbong.crm.perform.query.render.insert;

import com.xbongbong.crm.abstracts.AbstractCrmNewPageRenderService;
import com.xbongbong.crm.handle.explain.impl.OpportunityExplainHandleImpl;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DefaultTypeEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.DefaultAttrPoJo;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.RelyPoJo;
import com.xbongbong.paas.pojo.dto.FormDataAddGetDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.FormTemplateModel;
import com.xbongbong.saas.model.LinkProductRelyModel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 机会新建渲染页面
 * @author 吴峰
 * @date 2022/05/24 14:24
 */
@Service("opportunityNewPageRenderServiceImpl")
public class OpportunityNewPageRenderServiceImpl extends AbstractCrmNewPageRenderService {

    @Resource
    private LinkProductRelyModel linkProductRelyModel;
    @Resource
    private FormTemplateModel formTemplateModel;
    @Resource
    private OpportunityExplainHandleImpl opportunityExplainHandle;

    @Override
    public List<Integer> businessType() {
        return Arrays.asList(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
    }

    @Override
    public void businessHandleExplain(FormDataAddGetDTO formDataAddGetDTO, List<FieldAttrEntity> list, PaasFormEntityExt form) throws XbbException {
        String corpid = formDataAddGetDTO.getCorpid();
        Long formId = formDataAddGetDTO.getFormId();
        for (FieldAttrEntity fieldAttrEntity : list) {
            if (FieldTypeEnum.SELECT_PRODUCT.getType().equals(fieldAttrEntity.getFieldType())) {
                DefaultAttrPoJo defaultAttr = fieldAttrEntity.getDefaultAttr();
                if (Objects.nonNull(defaultAttr)) {
                    String defaultType = defaultAttr.getDefaultType();
                    if (DefaultTypeEnum.PRODUCT_DATA_RELY.getAlias().equals(defaultType)) {
                        List<RelyPoJo> relyPoJoList = linkProductRelyModel.selectProductRely(corpid, formId);
                        fieldAttrEntity.setRelyList(relyPoJoList);
                    }
                }
            }
        }
        FormatExplainDTO formatExplainDTO = new FormatExplainDTO(corpid, list);
        list = opportunityExplainHandle.newHandleExplain(formatExplainDTO);

        // 设置模板字段
        formTemplateModel.setTemplate(corpid, form, formDataAddGetDTO.getBusinessType(), formDataAddGetDTO.getLoginUser(), list, 1);
    }
}
